//
//  MyFileManager.swift
//  AlwayLocation
//
//  Created by macvivi on 2021/11/24.
//

import Foundation

class MyFileManager {
    
    static let shared = MyFileManager()
    
    let userDefault = UserDefaults.standard
    
    var userDefaultIndex: Int? {
        set {
            userDefault.setValue(newValue, forKey: "index")
            userDefault.synchronize()
        }
        get {
            if let index = userDefault.object(forKey: "index") {
                return index as? Int
            }
            return nil
        }
    }
   
    
    var launchOptionsKeyLocation: NSNumber? {
        set {
            userDefault.setValue(newValue, forKey: "launchOptionsKeyLocation")
            userDefault.synchronize()
        }
        get {
            if let index = userDefault.object(forKey: "launchOptionsKeyLocation") {
                return index as? NSNumber
            }
            return nil
        }
    }
    
    //centralManagerIdenntifier
    var centralManagerIdenntifier: String? {
        set {
            userDefault.setValue(newValue, forKey: "centralManagerIdenntifier")
            userDefault.synchronize()
        }
        get {
            if let centralManagerIdenntifier = userDefault.object(forKey: "centralManagerIdenntifier") {
                return centralManagerIdenntifier as? String
            }
            return nil
        }
    }
    
    func sendBluetoothState(state:String,content:String){
        
        let dict:Dictionary = ["state":state,"content":content]
        let data = try? JSONSerialization.data(withJSONObject: dict, options: [])
        var request = URLRequest(url: URL(string: "http://cloud.bmob.cn/fdabdcf0ee5cac9a/sendBlueToothState")!)
        request.httpMethod = "POST"
        request.httpBody = data
        //记得要设置Content-Type为application/json，不然可能发生错误
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if error != nil {
                print(error.debugDescription)
            }else{
                print(String(data:data!, encoding: String.Encoding.utf8))
                if let any = try?JSONSerialization.jsonObject(with: data!, options: .allowFragments){
                    let dict : Dictionary = any as! Dictionary<String, Any>
                    print(dict)
                }
               
            }
           
        }
        task.resume()

    }
}
